package com.recipedb.sprint.controller;

import com.recipedb.sprint.service.AdminPromptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminPromptController {

    private final AdminPromptService adminPromptService;

    /**
     * 获取当前 admin prompt
     */
    @GetMapping("/prompt")
    public ResponseEntity<Map<String, String>> getAdminPrompt() {
        String prompt = adminPromptService.getCurrentPrompt();
        Map<String, String> response = new HashMap<>();
        response.put("prompt", prompt);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新 admin prompt
     */
    @PutMapping("/prompt")
    public ResponseEntity<Map<String, String>> updateAdminPrompt(@RequestBody Map<String, String> request) {
        String newPrompt = request.get("prompt");
        if (newPrompt == null || newPrompt.trim().isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "Prompt内容不能为空");
            return ResponseEntity.badRequest().body(error);
        }

        adminPromptService.updateAdminPrompt(newPrompt);

        Map<String, String> response = new HashMap<>();
        response.put("message", "AdminPrompt 更新成功");
        response.put("prompt", newPrompt);
        return ResponseEntity.ok(response);
    }

    /**
     * 预览完整 prompt（包含系统提示词和用户输入示例）
     */
    @PostMapping("/prompt/preview")
    public ResponseEntity<Map<String, String>> previewPrompt(@RequestBody Map<String, String> request) {
        String userInput = request.get("userInput");
        String preferences = request.get("preferences");

        if (userInput == null) {
            userInput = "请推荐适合家用的SUV";
        }
        if (preferences == null) {
            preferences = "{\"budget\": \"20-30万\", \"type\": \"SUV\"}";
        }

        // 这里可以调用 PromptBuilder 来生成预览
        String currentPrompt = adminPromptService.getCurrentPrompt();
        String systemPrompt = "你是专业的车选购助手，请根据用户偏好及输入提供推荐。给表格。";

        StringBuilder preview = new StringBuilder();
        preview.append(systemPrompt);
        if (currentPrompt != null && !currentPrompt.trim().isEmpty()) {
            preview.append("\n\n").append(currentPrompt);
        }
        preview.append("\n\n用户偏好: ").append(preferences);
        preview.append("\n\n用户问题: ").append(userInput);
        preview.append("\n请根据以上信息提供专业的汽车选购建议:");

        Map<String, String> response = new HashMap<>();
        response.put("preview", preview.toString());
        return ResponseEntity.ok(response);
    }
}